#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
下载 pixi-live2d-display 的浏览器兼容版本(UMD格式)
"""

import urllib.request
import os
from pathlib import Path

def download_file(url, dest_path, file_name):
    """下载文件并显示进度"""
    print(f"\n正在下载 {file_name}...")
    print(f"URL: {url}")
    
    try:
        # 创建请求
        req = urllib.request.Request(
            url,
            headers={
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
        )
        
        # 下载文件
        with urllib.request.urlopen(req, timeout=60) as response:
            total_size = int(response.headers.get('Content-Length', 0))
            downloaded = 0
            
            # 写入文件
            with open(dest_path, 'wb') as f:
                while True:
                    chunk = response.read(8192)
                    if not chunk:
                        break
                    f.write(chunk)
                    downloaded += len(chunk)
                    
                    if total_size > 0:
                        progress = (downloaded / total_size) * 100
                        print(f"\r进度: {progress:.1f}% ({downloaded}/{total_size} bytes)", end='')
        
        print(f"\n✓ {file_name} 下载完成!")
        return True
        
    except Exception as e:
        print(f"\n✗ 下载失败: {e}")
        return False

def main():
    # 创建 libs 目录
    libs_dir = Path(__file__).parent / 'libs'
    libs_dir.mkdir(exist_ok=True)
    
    print("=" * 70)
    print("下载 pixi-live2d-display 浏览器版本")
    print("=" * 70)
    
    # 多个CDN源和版本尝试
    sources = [
        {
            'name': 'unpkg.com (v0.4.0)',
            'files': [
                {
                    'url': 'https://unpkg.com/pixi-live2d-display@0.4.0/dist/index.min.js',
                    'filename': 'pixi-live2d-display.min.js'
                },
                {
                    'url': 'https://unpkg.com/pixi-live2d-display@0.4.0/dist/cubism4.min.js',
                    'filename': 'pixi-live2d-display-cubism4.min.js'
                }
            ]
        },
        {
            'name': 'jsdelivr (v0.4.0)',
            'files': [
                {
                    'url': 'https://cdn.jsdelivr.net/npm/pixi-live2d-display@0.4.0/dist/index.min.js',
                    'filename': 'pixi-live2d-display.min.js'
                },
                {
                    'url': 'https://cdn.jsdelivr.net/npm/pixi-live2d-display@0.4.0/dist/cubism4.min.js',
                    'filename': 'pixi-live2d-display-cubism4.min.js'
                }
            ]
        },
    ]
    
    success = False
    for source in sources:
        print(f"\n尝试从 {source['name']} 下载...")
        all_files_ok = True
        
        for file_info in source['files']:
            dest_path = libs_dir / file_info['filename']
            
            if not download_file(file_info['url'], dest_path, file_info['filename']):
                all_files_ok = False
                break
        
        if all_files_ok:
            success = True
            print(f"\n✓ 所有文件下载成功!")
            break
        else:
            print(f"\n✗ {source['name']} 下载失败,尝试下一个源...")
    
    if success:
        print("\n" + "=" * 70)
        print("✓ 下载完成!")
        print(f"文件保存在: {libs_dir.resolve()}")
        
        # 验证文件
        for filename in ['pixi-live2d-display.min.js', 'pixi-live2d-display-cubism4.min.js']:
            file_path = libs_dir / filename
            if file_path.exists():
                file_size = file_path.stat().st_size
                print(f"  - {filename}: {file_size:,} bytes")
        
        print("=" * 70)
    else:
        print("\n" + "=" * 70)
        print("✗ 所有源都下载失败!")
        print("\n备用方案: 手动下载")
        print("1. 访问: https://github.com/guansss/pixi-live2d-display/releases")
        print("2. 下载最新的 dist 文件")
        print(f"3. 保存到: {libs_dir.resolve()}")
        print("=" * 70)

if __name__ == '__main__':
    main()
